<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>本月: 社保在缴 公积金在缴</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small">导入excel</el-button>
          <el-button type="danger" size="small">导出excel</el-button>
          <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="用户头像">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%;">
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- 方式一：$router.push(`/employees/detail?id=${row.id}`) 查询参数传递参数 -->
              <!--
                <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail?id=${row.id}`)"
              >查看</el-button>
               -->
              <!-- 方式二 路径传参 $router.push(`/employees/detail/${row.id}`) -->
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :page-sizes="[2,5,10,15,20]"
            @current-change="handleCurrentChange"
            @size-change="handSizeChange"
          />
        </el-row>
      </el-card>
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <addOrEdit ref="myEmp" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import addOrEdit from './empDialog.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
console.log(employeesEnum.hireType, 'employeesEnum.hireType')
// [{id:1,value:'正式'}，{id:2,value:'非正式'}]--->{1：正式，2：非正式}
// 将枚举中的数据遍历转换中 key和valuel的对象[{id:1,value:'正式'}，{id:2,value:非正式'}]--->{1:正式，2：非正式}
// 方式2
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// console.log(hireType, 'hireType')

// reduce完成数组遍历到对象中
// [1,2,3,4,5,6].reduce(('累计和','数组中的元素','索引号')=>{},'默认值')
// [{id:1,value:'正式'}，{id:2,value:'非正式'}]
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  // item => {id:1, value:'正式'}
  acc[item.id] = item.value
  return acc
}, {})

export default {
  components: {
    addOrEdit
  },
  data() {
    return {
      showDialog: false,
      list: [],
      page: 1, // 页码值
      size: 10, // 每页显示的条数
      total: 0
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 删除功能
    hDel(id) {
      this.$confirm('确定删除么?').then(async() => {
        const res = await delEmployee(id)
        if (this.list.length === 1) {
          this.page--
          if (this.page <= 0) {
            this.page = 1
          }
        }
        if (res.code === 10000) {
          this.loadEmployeeList()
        }
      }).catch(error => console.log(error))
    },
    // 重置表单
    hClose() {
      this.$refs.myEmp.resetForm()
    },
    hAdd() {
      this.showDialog = true
    },
    hSuccess() {
      // 新增成功里，关闭弹层，重新刷新页面
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      // 将当前的页码值切换到最后一页
      this.page = maxPage
      this.showDialog = false
      this.loadEmployeeList()
    },
    // 格式化聘用形式数据
    formatHireType(value) {
      // value的值有可能是1 || 2
      // console.log(value, 'value')
      // const obj = employeesEnum.hireType.find(item => item.id === value)
      // return obj ? obj.value : '未知'
      // 格式化的方式2 直接从转换的对象中根据键取值
      return hireType[value] || '未知'
    },
    handSizeChange(val) {
      console.log(`每页${val}条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      console.log(`当前页${val}条`)
      this.page = val
      this.loadEmployeeList()
    },
    // 获取员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.page, this.size)
        console.log(res, 'getEmployeeList')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
